<template>
    <div class="Login">
        <el-form :model="userInfo" :rules="rules" ref="loginRef" label-width="120px" status-icon class="LoginFrom">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="userInfo.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="userInfo.password" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @keyup.enter="keyDown" @click="login(loginRef)">登录</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script lang="ts" setup>
//setup语法糖 
import { reactive, ref } from 'vue'
import { userLogin } from '../request/api'
import { useStore } from 'vuex'
//引入自定义变量类型
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
//引入路由控制器
import { useRouter } from 'vue-router'
//设定路由控制器的方法
let router = useRouter()
let store = useStore()

//绑定数据表单
const userInfo = reactive({
    username: '',
    password: ''
})

//表单验证规则
const rules = reactive<FormRules>({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 8, message: '长度为2-8个字符', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 16, message: '长度为6-16个字符', trigger: 'blur' },
    ]
})

//封装登录事件
const loginRef = ref<FormInstance>()
const login = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((val) => {
        if (val) {
            userLogin(userInfo).then(res => {
                if (res.code == 200) {
                    ElMessage.success(res.msg)
                    //把登录信息存储到登录中
                    store.dispatch('changeUserInfo', res.list)
                    //跳转到index页面
                    router.push('index')
                } else {
                    ElMessage.error(res.msg)
                }
            })
        } else {
            console.log(val, '失败');
        }
    })
}

const keyDown = (e: any) => {
    //如果是回车则执行登录方法
    if (e.keyCode == 13) {
        //需要执行的登录方法
        login(loginRef.value);
    }
}

 //绑定事件
 window.addEventListener('keydown', keyDown);

</script>

<style lang="less" scoped>
.Login {
    width: 100vw;
    height: 100vh;
    line-height: 300px;
    background: #eaeaea;
    background-image: url('https://img0.baidu.com/it/u=4185393275,2673775235&fm=253&fmt=auto&app=138&f=JPEG?w=755&h=500');
    background-repeat: no-repeat;
    background-size:1700px;

    .LoginFrom {
        width: 400px;
        height: 300px;
        padding: 60px 50px 0 0;
        box-sizing: border-box;
        position: absolute;
        left: 50%;
        top: 50%;
        margin: -200px 0 0 -200px;
        background: rgb(145, 141, 247);
    }
}
</style>